%include "boot.inc"

section MBR vstart=0x7c00
	mov ax, cs
	mov ds, ax
	mov ss, ax
	mov es, ax
	mov fs, ax
	mov sp, 0x7c00
	mov ax, 0xb800
	mov gs, ax

; clear screen
	mov ah, 0x06
	mov al, 0x0
	mov bx, 0x700
	mov cx, 0x0
	mov dx, 0x184f
	int 0x10
	
; print
	mov ah, 0x13
	mov al, 0x01
	mov bh, 0x0
	mov bl, 0x07
	mov cx, [message_size]
	mov dh, 0x0
	mov dl, 0x0
	mov bp, message
	int 0x10

; load loader from disk
	mov eax, LOADER_START_SECTOR
	mov bx, LOADER_BASE_ADDR
	mov cx, LOADER_SECTOR_COUNT
	call read_disk_16

	jmp LOADER_BASE_ADDR

; =============================================================
; read disk sector in 16 bit real mode
; eax: LBA secctor
; bx: dst addr
; cx: sector count
read_disk_16:
	mov esi, eax
	mov di, cx

	; 1. sector count
	mov al, cl
	mov dx, 0x1f2
	out dx, al
	
	; 2. LBA
	mov eax, esi
	mov cl, 0x8

	; bit0-bit7
	mov dx, 0x1f3
	out dx, al

	; bit8-bit15
	mov dx, 0x1f4
	shr eax, cl
	out dx, al

	; bit16-bit23
	mov dx, 0x1f5
	shr eax, cl
	out dx, al

	; bit24-bit27
	mov dx, 0x1f6
	shr eax, cl
	and al, 0x0f
	or al, 0xe0	; device bit4-bit7
	out dx, al

	; 3. read command
	mov dx, 0x1f7
	mov al, 0x20
	out dx, al

	; 4. wait for readable
	mov dx, 0x1f7
.wait_for_readable:
	in al, dx
	and al,0x88
	cmp al, 0x8
	jnz .wait_for_readable

	; 5. read data
	mov ax, 256
	mul di
	mov cx, ax
	mov dx, 0x1f0
.read_data:
	in ax, dx
	mov [bx], ax
	add bx, 2
	loop .read_data

	ret
; =============================================================

message db "MyOS MBR start", 0x0A, 0x0D
message_size dw $ - message

times 510 - ($ - $$) db 0
db 0x55, 0xaa
